<!DOCTYPE html>  
<html>
<meta charset="utf-8" />  
<title>Router</title>  
<script language="javascript"type="text/javascript">  

</script>  
<body>
    <h2 id='h2'>Router</h2>  
    
    <button id='back'>back</button>
    <button id='forward'>forward</button>
    <button id='go'>go</button>
</body>
<script>
    // hash路由
    function Router(){
        this.currentUrl='';
        this.routes={};
        this.init();
    }
    Router.prototype.route = function(path,callback){
        this.routes[path] = callback || function(){}
    }
    Router.prototype.refresh = function(){
        this.currentUrl = location.hash.slice(1) || '/';
        this.routes[this.currentUrl]();
    }
    Router.prototype.init = function(){
        window.addEventListener('load',this.refresh.bind(this),false);
        window.addEventListener('hashchange',this.refresh.bind(this),false);
        // console.log(location.hash)
        // if(location.hash.slice(1)!=='/')
        //     location.hash = '#/';
    }


    var router = new Router();
        
    function changecolor(color){
        var body = document.getElementsByTagName('body')[0];
        body.style['background-color'] = color;
    }
    router.route('/',changecolor.bind(null,'red'));
    router.route('/blue',changecolor.bind(null,'blue'));
    router.route('/green',changecolor.bind(null,'green'));
    router.route('/color',function(){
        var p= document.getElementsByTagName('a');
        [].forEach.call(p,function(item){item.style['color'] = '#'+((~~(Math.random()*(1<<24))).toString(16));})
    });

    document.getElementById('back').onclick=function(){
        window.history.back()
    }

    document.getElementById('forward').onclick=function(){
        window.history.forward()
    }

    document.getElementById('go').onclick=function(){
        window.history.go(-1)
    }

    console.log(window.history)
</script>

</html>